<template>
  <HomepageMenu :menuList="menuList" style="height: 56px"></HomepageMenu>
  <div id="TaskTempletList">
    <Breadcrumb content="传输模版" />
    <el-container class="bodyContent">
      <Splitpanes>
        <Pane :size="(300 / conWidth) * 100">
          <vxe-button
            class="addRootBtn button-blue"
            type="text"
            icon="vxe-icon-add"
            content="新增根模块"
            @click="appendPPage()"
          ></vxe-button>

          <el-scrollbar style="height: calc(100% - 52px)">
            <div class="sampleType">
              <el-scrollbar>
                <el-tree
                  ref="leftTree"
                  :data="taskPageTree"
                  :props="defaultProps"
                  @node-click="handleNodeClick"
                  class="tools-tree"
                  node-key="id"
                  default-expand-all
                  highlight-current
                  :current-node-key="currentTreeId"
                >
                  <template #default="{ data }">
                    <span>{{ data.name }}</span>
                    <div class="cunston-tree-code">
                      <span>
                        <!-- 新增  -->
                        <el-button
                          type="success"
                          class="cirBtn"
                          size="small"
                          icon="Plus"
                          circle
                          @click="appendTaskPage(data)"
                        ></el-button>
                        <!-- 编辑  -->
                        <el-button
                          type="warning"
                          class="cirBtn"
                          size="small"
                          icon="Edit"
                          circle
                          @click="editTaskPage(data)"
                        ></el-button>
                        <!-- 删除  -->
                        <el-button
                          type="info"
                          class="cirBtn"
                          size="small"
                          icon="Delete"
                          circle
                          @click="removeTaskPage(data)"
                        ></el-button>
                      </span>
                    </div>
                  </template>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-scrollbar>

          <!-- 页面对话框 -->
          <el-dialog
            :title="titleType()"
            :show-close="false"
            v-model="showTaskPageDialog"
            append-to-body
            :close-on-click-modal="true"
            width="500px"
            style="height: 250px"
          >
            <el-form
              ref="taskPageFormRef"
              :model="taskPageForm"
              label-width="100px"
              class="form-input-m"
              :inline-message="true"
            >
              <el-form-item prop="name" label="页面名称">
                <el-input
                  type="text"
                  v-model="taskPageForm.name"
                  placeholder="请输入模块编号"
                ></el-input>
              </el-form-item>
              <el-form-item prop="code" label="页面编号">
                <el-input
                  type="text"
                  v-model="taskPageForm.code"
                  placeholder="请输入模块名称"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item prop="typeId" label="所属页面">
                <el-select v-model="taskPageForm.typeId" placeholder="请选择">
                  <el-option
                    v-for="item in pageOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer flex right justify-end">
              <el-button type="primary" @click="saveTaskPage()">保存</el-button>
              <el-button @click="closeTaskPageDialog()">取消</el-button>
            </div>
          </el-dialog>
        </Pane>

        <Pane :size="(1100 / conWidth) * 100"
          ><div class="models">
            <vxe-button
              class="addModels button-blue"
              type="text"
              icon="vxe-icon-add"
              content="新增模版"
              @click="addFormList()"
            ></vxe-button>

            <el-scrollbar style="height: calc(100% - 42px)">
              <div class="MiddleContent">
                <div v-for="(item, index) in taskTempletList" :key="index">
                  <el-card class="box-card">
                    <div class="card_header">
                      <span>数据传输模板 {{ index + 1 }}</span>
                      <div
                        class="dialogButtons flex right justify-end"
                        style="display: inline-block"
                      >
                        <vxe-button
                          class="button-green"
                          type="text"
                          icon="vxe-icon-radio-unchecked"
                          content="测试"
                          @click="testAdd(item)"
                        ></vxe-button>
                        <vxe-button
                          class="button-red"
                          type="text"
                          icon="vxe-icon-delete"
                          content="删除"
                          @click="removeTaskTemplet(item)"
                        ></vxe-button>
                        <vxe-button
                          class="button-blue"
                          type="text"
                          icon="vxe-icon-save"
                          content="保存"
                          @click="saveTemplet(index)"
                        ></vxe-button>
                      </div>
                    </div>

                    <el-form :ref="'form' + index" label-width="110px" :model="templetForms[index]">
                      <el-form-item label="任务标题">
                        <el-input v-model="templetForms[index].title"></el-input>
                      </el-form-item>
                      <el-form-item label="任务编码">
                        <el-input v-model="templetForms[index].code"></el-input>
                      </el-form-item>
                      <el-form-item label="任务类型">
                        <el-input v-model="templetForms[index].type"></el-input>
                      </el-form-item>
                      <el-form-item label="目标表">
                        <el-select
                          v-model="templetForms[index].targetTable"
                          @change="targetTableChange($event, index)"
                          placeholder="请选择"
                          size="default"
                        >
                          <template #prefix>
                            <PieChart style="width: 1em; height: 1em; margin-right: 8px"></PieChart>
                          </template>
                          <el-option
                            v-for="item in targetTableOptions"
                            :key="item.TABLE_NAME"
                            COMMENTS
                            :label="item.COMMENTS + '(' + item.TABLE_NAME + ')'"
                            :value="item.TABLE_NAME"
                          >
                            <span style="float: left">
                              <PieChart
                                style="width: 1em; height: 1em; margin-right: 8px; margin-top: 10px"
                              ></PieChart
                            ></span>
                            <span style="padding-left: 6px"
                              >{{ item.COMMENTS + '(' + item.TABLE_NAME + ')' }}
                            </span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="目标表字段">
                        <vxe-table
                          border
                          class="mytable-scrollbar"
                          ref="xTable"
                          height="auto"
                          align="center"
                          :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
                          :data="templetForms[index].targetTableColumnData"
                          keep-source
                          resizable
                          show-overflow
                        >
                          <vxe-column type="seq" width="30"></vxe-column>
                          <vxe-column field="columnName" title="字段编码" width="120"></vxe-column>
                          <vxe-column field="dataType" title="字段类型" width="100"></vxe-column>
                          <vxe-column field="comments" title="字段名称" width="120"></vxe-column>
                          <vxe-column
                            field="pageColumn"
                            title="页面字段"
                            show-overflow
                            width="470"
                            :edit-render="{ autofocus: '.vxe-input--inner' }"
                            align="left"
                          >
                            <template #edit="{ row }">
                              <el-input
                                type="textarea"
                                :autosize="{ minRows: 2, maxRows: 4 }"
                                placeholder="可以调节元素的高度"
                                v-model="row.pageColumn"
                                @click="handleInputBlur($event, index, row)"
                              >
                              </el-input>
                            </template>
                          </vxe-column>
                        </vxe-table>
                      </el-form-item>
                    </el-form>
                  </el-card>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <vxe-modal v-model="testModelDialog" width="900px" height="400px" :lock-scroll="false">
            <template #default>
              <vxe-form
                :data="testPageForm"
                size="small"
                height="auto"
                titleColon
                custom-layout
                span="11"
                class="TestForm"
              >
                <vxe-form-item
                  :title="p.chinaName"
                  :field="p.chinaName"
                  v-for="(p, pindex) in viewPageColumns"
                  :key="pindex"
                  :item-render="{}"
                >
                  <template #default="{ data }">
                    <vxe-input v-model="data[p.enName]" clearable></vxe-input>
                  </template>
                </vxe-form-item>
                <vxe-form-item align="center" span="24">
                  <template #default>
                    <vxe-button
                      type="text"
                      @click="testTempletTodo()"
                      content="提交"
                      icon="vxe-icon-checkbox-checked"
                      class="testSubmit button-blue"
                    ></vxe-button>
                  </template>
                </vxe-form-item>
              </vxe-form>

              <div class="modalTable">
                <vxe-table
                  border
                  height="auto"
                  class="mytable-scrollbar"
                  align="center"
                  ref="xTable1"
                  :data="testTableData"
                  show-footer
                  resizable
                  show-overflow
                >
                  <vxe-column type="seq" width="30"></vxe-column>
                  <vxe-column field="USER_NAME" title="代办人姓名" width="120"></vxe-column>
                  <vxe-column field="TODO_TIME" title="创建时间" width="100"></vxe-column>
                  <vxe-column field="TITLE" title="任务标题" width="120"></vxe-column>
                  <vxe-column field="CONTENT" title="任务内容" width="470"></vxe-column>
                </vxe-table>
              </div>
            </template>
          </vxe-modal>
        </Pane>
        <Pane>
          <el-scrollbar style="height: 100%">
            <div v-if="viewPageColumns.length > 0" class="pageColumns">
              <el-row :gutter="10">
                <el-col :span="12" v-for="(p, pindex) in viewPageColumns" :key="pindex">
                  <el-tag type="success" @click="insertPageColumn(p)">
                    {{ p.chinaName + '【' + p.enName + '】' }}
                  </el-tag>
                </el-col>
              </el-row>
            </div>
            <el-empty :image-size="200" style="height: 100%" v-else />
          </el-scrollbar>
        </Pane>
      </Splitpanes>
    </el-container>
  </div>
</template>
<script setup lang="ts">
// 引入组件区
import Breadcrumb from '@/components/Breadcrumb.vue';
import HomepageMenu from '@/components/HomePageMenu.vue';
import NoData from '@/components/NoData.vue'; //空状态
import { Splitpanes, Pane } from 'splitpanes';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { notifyType, notifyMessage } from '../../utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { AppStore } from '../../stores/store';
let store = AppStore();
// 获取屏幕宽度
let conWidth = ref(document.documentElement.clientWidth);

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let showTaskPageDialog = ref(false);
const moduleId = localStorage.getItem('moduleId');

let menuList: any = reactive([]);
let taskPageTree: any = reactive([]);
let defaultProps = reactive({
  children: 'children',
  label: 'name'
});
let taskTempletList: any = reactive([]);
let templetForms: any = reactive([]);
let taskPageForm = reactive({
  id: '',
  parentId: '',
  name: '',
  code: '',
  typeId: ''
});
let pageOptions = reactive([]);
let targetTableOptions: any = reactive([]);
let viewPageColumns: any = reactive([]);
let sltTaskPage: any = reactive({});
let cursorIndex: any = reactive({
  index: '',
  row: {}
});
let testModelDialog = ref(false);
let testTableData = reactive([]);
let testTempletTodoItem = reactive({
  code: '',
  id: ''
});
const testPageForm: any = reactive({
  pageCode: '',
  code: '',
  templetId: ''
});

// 方法定义区 =============
onMounted(() => {
  findTaskPageTree();
  findTableNames();
  getpageOptions();
  getMenuList();
});

// 测试预览
function testAdd(item: any) {
  testModelDialog.value = true;
  testTempletTodoItem = item;
  viewPageColumns.forEach((item: any) => {
    testPageForm[item.enName] = '';
  });
  // 获取模版列表
  findTaskTempletTestList(item);
}
// 测试数据插入
function testTempletTodo() {
  const url = '/api/task/public/pageInfoAddTransmitTodoTable';
  testPageForm.pageCode = sltTaskPage.code;
  testPageForm.code = testTempletTodoItem.code;
  testPageForm.templetId = testTempletTodoItem.id;
  proxy.$http
    .post(url, testPageForm)
    .then((res: any) => {
      notifyMessage(res.status.msg, notifyType.success, proxy);
      findTaskTempletTestList(testTempletTodoItem);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 获取菜单树型数据
function getMenuList() {
  // 通过权限信息获取菜单
  let moduleMenuMap = store.userInfo.moduleMenuMap;
  if (Object.keys(moduleMenuMap).includes(moduleId)) {
    menuList.push(...moduleMenuMap[moduleId]);
  }
}
// 获取所有界面字典
function getpageOptions() {
  const url = '/api/sys/basDict/findDictListByType';
  proxy.$http
    .get(url, { params: { code: 'znmb', grade: 0 } })
    .then((res: any) => {
      pageOptions.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 获取界面字段
function getPageColumns() {
  viewPageColumns.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { pid: sltTaskPage.typeId } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        // 设置界面字典
        viewPageColumns.push(...res.data);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 当前树选中行的id
let currentTreeId = ref('');

// 获取页面列表
function findTaskPageTree() {
  taskPageTree.length = 0; //清空数据
  const url = '/api/task/page/getTaskPageListTree';
  proxy.$http
    .get(url)
    .then((res: any) => {
      taskPageTree.push(...res.data);
      if (taskPageTree.length > 0) {
        if (taskPageTree[0].children.length !== 0) {
          const firstId = taskPageTree[0].children[0].id;
          currentTreeId.value = firstId;
        } else {
          const firstId = taskPageTree[0].id;
          currentTreeId.value = firstId;
        }
        proxy.$nextTick(() => {
          proxy.$refs.leftTree.setCurrentKey(currentTreeId.value);
          handleNodeClick(taskPageTree[0].children ? taskPageTree[0].children[0] : taskPageTree[0]); //默认点击当前树中第一个
        });
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 获取模版列表
function findTaskTempletList() {
  taskTempletList.length = 0;
  templetForms.length = 0;
  const url = '/api/task/templet/findTaskTempletListByPageId/' + sltTaskPage.id;
  proxy.$http
    .get(url)
    .then((res: any) => {
      taskTempletList.push(...res.data);
      templetForms.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 获取模版列表
function findTaskTempletTestList(templet: any) {
  testTableData.length = 0;
  const url = '/api/task/templet/getTempletTestList/' + templet.targetTable + '/' + templet.id;
  proxy.$http
    .get(url)
    .then((res: any) => {
      testTableData.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 获取目标表options
function findTableNames() {
  const url = '/api/task/public/findTableNames';
  proxy.$http
    .get(url)
    .then((res: any) => {
      targetTableOptions.push(...res.data);
    })
    .catch((err: any) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}
// 获取目标表字段
function findTableColumns(tableName: any, index: any) {
  const url = '/api/task/public/findColumnsByTableName/' + tableName;
  proxy.$http
    .get(url)
    .then((res: any) => {
      templetForms[index].targetTableColumnData = res.data;
    })
    .catch((err: any) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}
// 新增任务页面
function appendTaskPage(data: any) {
  taskPageForm.parentId = data.id;
  showTaskPageDialog.value = true;
}
// 添加根节点
function appendPPage() {
  taskPageForm.parentId = '0';
  showTaskPageDialog.value = true;
}

function closeTaskPageDialog() {
  taskPageForm.parentId = '';
  (taskPageForm.id = ''),
    (taskPageForm.name = ''),
    (taskPageForm.code = ''),
    (taskPageForm.typeId = ''),
    (showTaskPageDialog.value = false);
}
// 编辑任务页面
function editTaskPage(item: any) {
  taskPageForm.parentId = item.parentId;
  taskPageForm.id = item.id;
  taskPageForm.name = item.name;
  taskPageForm.code = item.code;
  taskPageForm.typeId = item.typeId;
  showTaskPageDialog.value = true;
}

function saveTaskPage() {
  const taskPageObject = {
    id: taskPageForm.id,
    parentId: taskPageForm.parentId,
    orgId: '1',
    typeId: taskPageForm.typeId,
    name: taskPageForm.name,
    code: taskPageForm.code
  };
  let url = '';
  if (taskPageObject.id) {
    url = '/api/task/page/editTaskPage';
  } else {
    url = '/api/task/page/addTaskPage';
  }
  proxy.$http
    .post(url, taskPageObject)
    .then((res: any) => {
      if (res.status.code !== 1) {
        VxeMessage('保存失败', VxeNotifyType.error);
      } else {
        VxeMessage('保存成功', VxeNotifyType.success);
        showTaskPageDialog.value = false;
      }
      // 重新获取数据
      findTaskPageTree(); //获取页面树
    })
    .catch((err: any) => {
      // notifyMessage(err, notifyType.warning, proxy);
      VxeMessage('保存异常', VxeNotifyType.error);
    });
}
// 删除树节点
function removeTaskPage(row: any) {
  proxy
    .$confirm('确定删除此模块？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/task/page/deleteTaskPage/' + row.id;
      proxy.$http
        .delete(url)
        .then((res: any) => {
          VxeMessage('删除成功', VxeNotifyType.success);
          findTaskPageTree();
        })
        .catch((err: any) => {
          VxeMessage('删除失败', VxeNotifyType.error);
        });
    });
}

// 点击树节点
function handleNodeClick(data: any) {
  viewPageColumns.length = 0;
  sltTaskPage = data;
  findTaskTempletList(); //获取模版列表
  // 父级不要获取界面字段
  if (data.parentId !== '0') {
    getPageColumns(); //获取界面字段
  }
}
function targetTableChange(item: any, index: any) {
  findTableColumns(item, index); //获取目标表字段
}
// 添加模版
function addFormList() {
  taskTempletList.length = taskTempletList.length + 1;
  let templetForm = {
    title: '',
    code: '',
    type: '',
    formula: '',
    targetTable: '',
    pageId: sltTaskPage.id,
    pageCode: sltTaskPage.code,
    targetTableColumnData: [],
    testTableData: []
  };
  templetForms.push(templetForm);
}
// 保存模版
function saveTemplet(index: any) {
  let url = '';
  if (templetForms[index].id) {
    url = '/api/task/templet/editTaskTemplet';
  } else {
    url = '/api/task/templet/addTaskTemplet';
  }
  proxy.$http
    .post(url, templetForms[index])
    .then((res: any) => {
      if (res.status.code !== 1) {
        VxeMessage('修改模版失败', VxeNotifyType.error);
      } else {
        VxeMessage('修改模版成功', VxeNotifyType.success);
      }
      findTaskTempletList(); //重新获取模版列表
    })
    .catch((err: any) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}
// 删除模版
function removeTaskTemplet(row: any) {
  proxy
    .$confirm('确定删除此模版？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/task/templet/deleteTaskTemplet';
      proxy.$http
        .post(url, row)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('删除成功', VxeNotifyType.success);
          } else {
            VxeMessage('删除失败', VxeNotifyType.error);
          }
          findTaskTempletList(); //重新获取模版列表
        })
        .catch((err: any) => {
          VxeMessage('删除异常', VxeNotifyType.error);
        });
    });
}

// 判断弹框显示的标题
function titleType() {
  if (taskPageForm.id) {
    return `编辑`;
  } else if (!taskPageForm.id) {
    return `新建`;
  }
}
// 鼠标点击事件
function handleInputBlur(e, index, row) {
  cursorIndex.value = e.srcElement.selectionStart;
  cursorIndex.index = index;
  cursorIndex.row = row;
}
// 在鼠标点击位置插入字段值
function insertPageColumn(tag) {
  if (cursorIndex.value) {
    let datas = templetForms[cursorIndex.index].targetTableColumnData;
    let row = datas.find((item) => item.columnName === cursorIndex.row.columnName);
    let pageColumnStr = row.pageColumn + '';
    let resultPageColumnStr = '';
    if (pageColumnStr.length <= cursorIndex.value) {
      resultPageColumnStr = pageColumnStr + '{' + tag.enName + '}';
    } else {
      let s1 = pageColumnStr.substring(0, cursorIndex.value);
      let s2 = pageColumnStr.substring(cursorIndex.value, pageColumnStr.length);
      resultPageColumnStr = s1 + '{' + tag.enName + '}' + s2;
    }
    templetForms[cursorIndex.index].targetTableColumnData.map((item) => {
      if (item.columnName == row.columnName) {
        item.pageColumn = resultPageColumnStr;
      }
      return item;
    });
  }
}
</script>
<style lang="scss" scoped>
#TaskTempletList {
  width: 100%;
  height: calc(100% - 56px);
  // 卡片下的阴影
  .el-card.is-always-shadow {
    box-shadow: none;
  }
  // 滚动条的位置
  :deep(.el-scrollbar__bar) {
    right: 4px !important;
  }
  // 空状态的位置
  :deep(.el-empty__image) {
    position: absolute;
    top: 25%;
  }
  :deep(.el-empty__description) {
    position: absolute;
    top: 49%;
  }
  .bodyContent {
    height: calc(100% - 40px);
  }

  .splitpanes {
    .splitpanes__pane {
      background-color: $base-white;
      // 最左侧新增根模块
      .addRootBtn {
        margin: 10px 10px 0 10px !important;
      }
      // 最左侧的树
      .sampleType {
        height: calc(100% - 52px);
        // el-tree
        .tools-tree {
          min-width: 168px;
          padding: 5px;
          font-size: $font-size;
          border: none;
          .cirBtn {
            display: none;
            width: 16px;
            height: 16px;
            padding: 0px;
            margin-left: 10px;
          }
          .el-tree-node__content:hover {
            .cirBtn {
              display: inline-block !important;
            }
          }
        }
      }
      // 中间区域
      .models {
        height: 100%;
        //中间新增模版
        .addModels {
          margin: 10px !important;
        }
        :deep(.el-scrollbar) {
          padding: 0 10px 0 10px;
        }
        .MiddleContent {
          height: calc(100% - 52px);
          // 数据传输模版卡片
          .box-card {
            margin-bottom: 10px;
            // 卡片里的内边距
            :deep(.el-card__body) {
              padding: 0 10px 15px 0;
            }
            // 卡片里的input输入框
            :deep(.el-input) {
              width: 400px !important;
            }
            // 卡片头部按钮区域
            .card_header {
              display: flex;
              align-items: center;
              justify-content: space-between;
              span {
                font-size: $font-size-m;
                padding: 10px;
              }
            }

            // form表单里每一个table的行高度
            :deep(.vxe-body--row) {
              height: 40px !important;
            }
            // 可拖拉文本域
            .vxe-textarea {
              margin-top: -14px;
            }
          }
        }
      }
      // 测试预览的form表单
      .TestForm {
        :deep(.vxe-form--item) {
          margin-right: 20px;
        }
        .testSubmit {
          display: flex;
          align-items: center;
          float: right;
        }
      }

      // 测试预览的table

      .modalTable {
        height: 100%;
      }

      // 最右侧的tag显示
      .pageColumns {
        width: 100%;
        height: 100%;
        padding: 10px 0 10px 10px;
        .el-row {
          width: calc(100% - 20px);
          margin-left: 0 !important;
          margin-right: 0 !important;
          .el-tag {
            width: 100%;
            text-align: left;
            padding: 15px;
            margin-bottom: 10px;
            font-size: $font-size;
            min-width: 225px;
          }
        }
      }
    }
  }
}
</style>
